package com.tianji.learning.mq;

import cn.hutool.core.util.ObjectUtil;
import com.tianji.api.dto.trade.OrderBasicDTO;
import com.tianji.learning.service.ILearningLessonService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import static com.tianji.common.constants.MqConstants.Exchange.*;
import static com.tianji.common.constants.MqConstants.Key.*;
import static com.tianji.common.constants.MqConstants.Queue.*;

/**
 * @author Waker
 * @description:
 * @create 2025-10-18-15:32
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class LessonChangeListener {

    private final ILearningLessonService learningLessonService;

    /**
     * 1. 监听订单支付成功消息-> 新增课程到用户的课表
     *
     * @param orderMsg
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = LEARNING_LESSON_PAY_QUEUE, durable = "true"),
            exchange = @Exchange(name = ORDER_EXCHANGE, type = ExchangeTypes.TOPIC),
            key = ORDER_PAY_KEY
    ))
    public void listenOrderPayMsg(OrderBasicDTO orderMsg) {
        // 1. 消息健壮性判断
        if (ObjectUtil.isEmpty(orderMsg) || ObjectUtil.isEmpty(orderMsg.getCourseIds()) || ObjectUtil.isEmpty(orderMsg.getUserId())) {
            log.error("订单支付成功消息参数错误：{}", orderMsg);
            return;
        }
        // 2. 添加课程到用户课表
        log.info("监听到用户：{}的订单支付消息，订单ID：{}，需要添加课程：{} 到用户的课表", orderMsg.getUserId(),orderMsg.getOrderId(),orderMsg.getCourseIds());
        learningLessonService.addLessons(orderMsg.getUserId(), orderMsg.getCourseIds());
    }

    /**
     * 2. 监听订单退款成功消息-> 删除用户课表中的课程
     * @param orderMsg
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = LEARNING_LESSON_REFUND_QUEUE, durable = "true"),
            exchange = @Exchange(name = ORDER_EXCHANGE, type = ExchangeTypes.TOPIC),
            key = ORDER_REFUND_KEY
    ))
    public void listenOrderRefundMsg(OrderBasicDTO orderMsg){
        // 1. 消息健壮性判断
        if (ObjectUtil.isEmpty(orderMsg) || ObjectUtil.isEmpty(orderMsg.getCourseIds()) || ObjectUtil.isEmpty(orderMsg.getUserId())) {
            log.error("订单退款成功消息参数错误：{}", orderMsg);
            return;
        }
        // 2. 删除用户课表中的课程
        log.info("监听到用户：{}的订单退款消息，订单ID：{}，需要从用户的课表删除课程：{} ", orderMsg.getUserId(),orderMsg.getOrderId(),orderMsg.getCourseIds());
        learningLessonService.deleteRefundLesson(orderMsg.getUserId(),orderMsg.getCourseIds());
    }
}
